package myserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
import java.util.TreeSet;

public class ServerFileTransfer {
	TreeMap<Integer,BufferedOutputStream> receiveMap = new TreeMap<Integer, BufferedOutputStream>();
	TreeMap<Integer,ThreadFile> sendMap = new TreeMap<Integer, ThreadFile>();
	TreeSet<Integer> treeSet = new TreeSet<Integer>();
	int max=0;
	
	public ServerFileTransfer(){
		for(int i=max;i<max+100;i++){
			treeSet.add(i);
		}
		max=+100;
	}
	public int getNum(){
		if(treeSet.size()==0){
			for(int i=max;i<max+100;i++){
				treeSet.add(i);
			}
			max =+ 100;
		}
		return treeSet.pollFirst().intValue();
	}
	
	//传两个参数,进行Socket连接
	public void makeSocket(int port1){
		try {
			ServerSocket ss = new ServerSocket(port1);
			Socket s1 = ss.accept();
			BufferedInputStream input1 = new BufferedInputStream(s1.getInputStream());
			//先读取它是属于哪个数组
			int num1 = input1.read();
			//再读取它是属于收还是发  0是收，1是发
			int or1 = input1.read();
			if(or1==0){//如果是收
				receiveMap.put(num1, new BufferedOutputStream(s1.getOutputStream()));
			}else if(or1==1){//发送方
				ThreadFile sendThread1 = new ThreadFile(this,input1,num1);
				sendMap.put(num1, sendThread1);
			}
			
			
			
			Socket s2 = ss.accept();
			BufferedInputStream input2 = new BufferedInputStream(s2.getInputStream());
			//先读取它是属于哪个数组
			int num2 = input2.read();
			//再读取它是属于收还是发  0是收，1是发
			int or2 = input2.read();
			if(or2==0){//如果是收
				receiveMap.put(num2, new BufferedOutputStream(s2.getOutputStream()));
				if(sendMap.containsKey(num2)){
					sendMap.get(num2).start();
				}
			}else if(or2==1){//发送方
				ThreadFile sendThread2 = new ThreadFile(this,input2,num2);
				sendMap.put(num2, sendThread2);
				if(receiveMap.containsKey(num2)){
					sendThread2.start();
				}
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
//多线程类，用来接收并发传送文件的类
class ThreadFile extends Thread{
	ServerFileTransfer transfer;
	BufferedInputStream input;
	int num;
	public ThreadFile(ServerFileTransfer transfer,BufferedInputStream input,int num){
		this.transfer = transfer;
		this.input = input;
		this.num = num;
	}
	public void run(){
		byte[] buf = new byte[4096];
		int len=0;
		try {
			while((len=input.read(buf))!=-1){
				transfer.receiveMap.get(num).write(buf, 0, len);
				transfer.receiveMap.get(num).flush();
			}
			transfer.receiveMap.get(num).close();
//System.out.println("server发送完毕");
			ServerFrame.area.append("server发送完毕/n");
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
